//
//  ViewController.m
//  引导页
//
//  Created by li cheng on 16/7/21.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "ViewController.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
BOOL isOut = NO;
@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIPageControl *page;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
    if (![userDefaults objectForKey:@"Hello"]) {
        [self foundScrollView];
        [self foundPage];
        [userDefaults setObject:@"Come" forKey:@"Hello"];
    }
}

#pragma mark - 创建ScrollView
- (void)foundScrollView{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    scrollView.delegate = self;
    scrollView.pagingEnabled = YES;
    [self.view addSubview:scrollView];
    NSArray *arrayOfImages = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
    scrollView.contentSize = CGSizeMake(WIDTH * arrayOfImages.count, 0);
    scrollView.contentOffset = CGPointMake(WIDTH, 0);
    for (int i = 0; i < arrayOfImages.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, HEIGHT)];
        imageView.image = [UIImage imageNamed:arrayOfImages[i]];
        [scrollView addSubview:imageView];
    }
    
}

#pragma mark - 创建分页控制器
- (void)foundPage{
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH / 2 - 50, HEIGHT - 80, 100, 20)];
    [self.view addSubview:_page];
    // 当前页数
    self.page.currentPage = 0;
    // 总页数
    self.page.numberOfPages = 4;

}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x > WIDTH * 3 + 30) {
        isOut = YES;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (isOut) {
        self.page.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width;
        [UIView animateWithDuration:1.5 animations:^{
            scrollView.alpha = 0; // 让scrollView渐变消失
        } completion:^(BOOL finished) {
            [scrollView removeFromSuperview];
            [self.page removeFromSuperview];
        }];
    }
}





//- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
//    return [scrollView.subviews firstObject];
//}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
